﻿using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Xml.Linq;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.LIB;
using YJKMenuAssist.DataManagement;
using YJKMenuAssist.MenuManageControls;
using YJKMenuAssist.Utility;

namespace YJKMenuAssist.Controls
{
	public partial class AutoKeyBoardTab : System.Windows.Controls.UserControl, IComponentConnector
	{
		public AutoKeyBoardTab()
		{
			this.InitializeComponent();
			this.btnAdd.IsEnabled = false;
			this.btnDelete.IsEnabled = false;
		}

		internal void IniData(CommandTableInfos commandTableInfos, ExternalCommandData commandData, string strKeyFile)
		{
			this.m_CommandTableInfos = commandTableInfos;
			this.m_CommandData = commandData;
			this.leftList.IniTreeData(commandTableInfos);
			this.SetKeyBoard(strKeyFile);
			this.leftList.tvProperties.SelectedItemChanged += this.tvProperties_SelectedItemChanged;
		}

		private void tvProperties_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
		{
			PropertyNodeItem propertyNodeItem = this.leftList.tvProperties.SelectedItem as PropertyNodeItem;
			this.RefreshContral(propertyNodeItem.Parent, propertyNodeItem.DisplayName, this.m_CommandTableInfos);
		}

		public void SetKeyBoard(string strShortcutsPath)
		{
			XElement rootNode = XElement.Load(strShortcutsPath);
			this.m_DicKeyBoard.Clear();
			for (int i = 0; i < this.m_CommandTableInfos.TableInofList.Count; i++)
			{
				TableInfos tableInfos = this.m_CommandTableInfos.TableInofList[i];
				for (int j = 0; j < tableInfos.CommandInfoList.Count; j++)
				{
					if (tableInfos.CommandInfoList[j].LstCommandInfos.Count == 0)
					{
						tableInfos.CommandInfoList[j].KeyBoardName = ShortcutsFile.GetShortcuts(tableInfos.CommandInfoList[j], rootNode, tableInfos.TableName);
						this.AddKeyToList(tableInfos.CommandInfoList[j].KeyBoardName, tableInfos.CommandInfoList[j]);
					}
					else
					{
						foreach (CommandInfos commandInfos in tableInfos.CommandInfoList[j].LstCommandInfos)
						{
							commandInfos.KeyBoardName = ShortcutsFile.GetShortcuts(commandInfos, rootNode, tableInfos.TableName);
							this.AddKeyToList(commandInfos.KeyBoardName, commandInfos);
						}
					}
				}
			}
		}

		private void AddKeyToList(string strKey, CommandInfos commandInfos)
		{
			try
			{
				if (strKey != string.Empty)
				{
					string[] array = strKey.Split(new char[]
					{
						'#'
					});
					if (array.Length > 1)
					{
						foreach (string key in array)
						{
							this.m_DicKeyBoard.Add(key, commandInfos);
						}
					}
					else
					{
						this.m_DicKeyBoard.Add(strKey, commandInfos);
					}
				}
			}
			catch
			{
			}
		}

		private void RefreshContral(string parentName, string displayName, CommandTableInfos commandTableInfos)
		{
			this.dataGrid.Items.Clear();
			for (int i = 0; i < commandTableInfos.TableInofList.Count; i++)
			{
				TableInfos tableInfos = commandTableInfos.TableInofList[i];
				if (displayName == tableInfos.TableName)
				{
					for (int j = 0; j < tableInfos.CommandInfoList.Count; j++)
					{
						this.AddData(tableInfos.CommandInfoList[j], parentName, displayName);
					}
				}
			}
			this.dataGrid.SelectedIndex = 0;
		}

		private void AddData(CommandInfos commandInfos, string parentName, string displayName)
		{
			if (commandInfos.LstCommandInfos.Count == 0)
			{
				this.HasMoreKeyBoard(commandInfos, parentName, displayName);
				return;
			}
			foreach (CommandInfos commandInfos2 in commandInfos.LstCommandInfos)
			{
				this.HasMoreKeyBoard(commandInfos2, parentName, displayName);
			}
		}

		private void AddData(CommandInfos commandInfos, string tableName)
		{
			string strXmlPathFileName = Path.Combine(Product.UserDataLocation, "CustomMenu.xml");
			if (commandInfos.LstCommandInfos.Count == 0)
			{
				string cmdPath = XmlManager.GetCmdPath(commandInfos, strXmlPathFileName);
				this.HasMoreKeyBoard(commandInfos, cmdPath, tableName);
				return;
			}
			foreach (CommandInfos commandInfos2 in commandInfos.LstCommandInfos)
			{
				string cmdPath2 = XmlManager.GetCmdPath(commandInfos2, strXmlPathFileName);
				this.HasMoreKeyBoard(commandInfos2, cmdPath2, tableName);
			}
		}

		private void HasMoreKeyBoard(CommandInfos commandInfos, string parentName, string displayName)
		{
			string[] array = commandInfos.KeyBoardName.Split(new char[]
			{
				'#'
			});
			if (array.Length > 1)
			{
				for (int i = 0; i < array.Length; i++)
				{
					string cmdName = "";
					if (i == 0)
					{
						cmdName = commandInfos.CmdName;
					}
					this.dataGrid.Items.Add(new KeyBoardItem
					{
						CmdName = cmdName,
						KeyBoard = array[i],
						CmdPath = string.Concat(new string[]
						{
							parentName,
							"-",
							displayName,
							"-",
							commandInfos.PanelName
						}),
						CommandInfos = commandInfos
					});
				}
				return;
			}
			this.dataGrid.Items.Add(new KeyBoardItem
			{
				CmdName = commandInfos.CmdName,
				KeyBoard = commandInfos.KeyBoardName,
				CmdPath = string.Concat(new string[]
				{
					parentName,
					"-",
					displayName,
					"-",
					commandInfos.PanelName
				}),
				CommandInfos = commandInfos
			});
		}

		private void textBox_LostFocus(object sender, RoutedEventArgs e)
		{
			try
			{
				PropertyNodeItem propertyNodeItem = this.leftList.tvProperties.SelectedItem as PropertyNodeItem;
				this.RefreshContral(propertyNodeItem.Parent, propertyNodeItem.DisplayName, this.m_CommandTableInfos);
			}
			catch
			{
			}
		}

		private void textBox_GotFocus(object sender, RoutedEventArgs e)
		{
			System.Windows.Controls.TextBox textBox = (System.Windows.Controls.TextBox)sender;
			this.SearchKeywords(textBox.Text, this.m_CommandTableInfos);
		}

		private void textBox_TextChanged(object sender, TextChangedEventArgs e)
		{
			System.Windows.Controls.TextBox textBox = (System.Windows.Controls.TextBox)sender;
			this.SearchKeywords(textBox.Text, this.m_CommandTableInfos);
		}

		public void SearchKeywords(string cmdName, CommandTableInfos commandTableInfos)
		{
			this.dataGrid.Items.Clear();
			for (int i = 0; i < commandTableInfos.TableInofList.Count; i++)
			{
				TableInfos tableInfos = commandTableInfos.TableInofList[i];
				for (int j = 0; j < tableInfos.CommandInfoList.Count; j++)
				{
					if (tableInfos.CommandInfoList[j].CmdName.Contains(cmdName) && string.Empty != cmdName)
					{
						this.AddData(tableInfos.CommandInfoList[j], tableInfos.TableName);
					}
				}
			}
		}

		private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			try
			{
				if (this.dataGrid.SelectedItem != null)
				{
					this.btnDelete.IsEnabled = true;
					this.btnAdd.IsEnabled = true;
				}
				else
				{
					this.btnDelete.IsEnabled = false;
					this.btnAdd.IsEnabled = false;
				}
			}
			catch
			{
				this.btnDelete.IsEnabled = false;
				this.btnAdd.IsEnabled = false;
			}
		}

		private void txtKey_TextChanged(object sender, TextChangedEventArgs e)
		{
		}

		private void btnAdd_Click(object sender, RoutedEventArgs e)
		{
			KeyBoardItem keyBoardItem = this.dataGrid.SelectedItem as KeyBoardItem;
			int selectedIndex = this.dataGrid.SelectedIndex;
			if (this.CheckKeyBoard(this.txtKey.Text, keyBoardItem, ref selectedIndex))
			{
				if (keyBoardItem.KeyBoard == "")
				{
					this.SetCellValue(this.txtKey.Text);
					keyBoardItem.KeyBoard = this.txtKey.Text;
					keyBoardItem.CommandInfos.KeyBoardName = this.txtKey.Text;
				}
				else if (keyBoardItem.CommandInfos.KeyBoardName.Split(new char[]
				{
					'#'
				}).Length < 5 && this.txtKey.Text != keyBoardItem.KeyBoard)
				{
					this.dataGrid.Items.Insert(this.dataGrid.SelectedIndex + 1, new KeyBoardItem
					{
						CmdName = "",
						KeyBoard = this.txtKey.Text,
						CmdPath = keyBoardItem.CmdPath,
						CommandInfos = keyBoardItem.CommandInfos
					});
					CommandInfos commandInfos = keyBoardItem.CommandInfos;
					commandInfos.KeyBoardName = commandInfos.KeyBoardName + "#" + this.txtKey.Text;
				}
				try
				{
					PropertyNodeItem propertyNodeItem = this.leftList.tvProperties.SelectedItem as PropertyNodeItem;
					this.RefreshContral(propertyNodeItem.Parent, propertyNodeItem.DisplayName, this.m_CommandTableInfos);
					this.dataGrid.SelectedIndex = selectedIndex;
				}
				catch
				{
				}
			}
		}

		private bool CheckKeyBoard(string keyBoard, KeyBoardItem keyBoardItem, ref int iSelectedIndex)
		{
			if (keyBoard == string.Empty)
			{
				return false;
			}
			if (!this.m_DicKeyBoard.ContainsKey(keyBoard))
			{
				bool result;
				try
				{
					this.m_DicKeyBoard.Add(keyBoard, keyBoardItem.CommandInfos);
					result = true;
				}
				catch
				{
					result = false;
				}
				return result;
			}
			if (!(keyBoardItem.CommandInfos.CmdId != this.m_DicKeyBoard[keyBoard].CmdId))
			{
				return false;
			}
			if (YJKMessageBox.Show("当前快捷键与功能" + this.m_DicKeyBoard[keyBoard].CmdName + "发生重复，是否确定替换该快捷键？", MessageBoxButtons.OKCancel, MessageBoxIcon.None) == DialogResult.OK)
			{
				if (this.m_DicKeyBoard[keyBoard].KeyBoardName.Contains("#"))
				{
					this.m_DicKeyBoard[keyBoard].KeyBoardName = this.m_DicKeyBoard[keyBoard].KeyBoardName.Replace("#" + keyBoard, "");
					this.m_DicKeyBoard[keyBoard].KeyBoardName = this.m_DicKeyBoard[keyBoard].KeyBoardName.Replace(keyBoard + "#", "");
					iSelectedIndex--;
				}
				else
				{
					this.m_DicKeyBoard[keyBoard].KeyBoardName = "";
				}
				this.ModifySameCmd(this.m_DicKeyBoard[keyBoard]);
				this.m_DicKeyBoard.Remove(keyBoard);
				this.m_DicKeyBoard.Add(keyBoard, keyBoardItem.CommandInfos);
				return true;
			}
			return false;
		}

		private void ModifySameCmd(CommandInfos commandInfos)
		{
			for (int i = 0; i < this.m_CommandTableInfos.TableInofList.Count; i++)
			{
				TableInfos tableInfos = this.m_CommandTableInfos.TableInofList[i];
				for (int j = 0; j < tableInfos.CommandInfoList.Count; j++)
				{
					if (tableInfos.CommandInfoList[j].LstCommandInfos.Count == 0)
					{
						if (tableInfos.CommandInfoList[j].CmdId == commandInfos.CmdId)
						{
							tableInfos.CommandInfoList[j].KeyBoardName = commandInfos.KeyBoardName;
						}
					}
					else
					{
						foreach (CommandInfos commandInfos2 in tableInfos.CommandInfoList[j].LstCommandInfos)
						{
							if (commandInfos2.CmdId == commandInfos.CmdId)
							{
								commandInfos2.KeyBoardName = commandInfos.KeyBoardName;
							}
						}
					}
				}
			}
		}

		private void SetCellValue(string strValue)
		{
			DataGridRow dataGridRow = (DataGridRow)this.dataGrid.ItemContainerGenerator.ContainerFromIndex(this.dataGrid.SelectedIndex);
			if (dataGridRow != null)
			{
				DataGridCellsPresenter visualChild = AutoKeyBoardTab.GetVisualChild<DataGridCellsPresenter>(dataGridRow);
				System.Windows.Controls.DataGridCell dataGridCell = (System.Windows.Controls.DataGridCell)visualChild.ItemContainerGenerator.ContainerFromIndex(1);
				if (dataGridCell == null)
				{
					dataGridCell = (System.Windows.Controls.DataGridCell)visualChild.ItemContainerGenerator.ContainerFromIndex(1);
				}
				dataGridCell.Width = 70.0;
				dataGridCell.Content = strValue;
				dataGridCell.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
			}
		}

		public static T GetVisualChild<T>(Visual parent) where T : Visual
		{
			T t = default(T);
			int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
			for (int i = 0; i < childrenCount; i++)
			{
				Visual visual = (Visual)VisualTreeHelper.GetChild(parent, i);
				t = (visual as T);
				if (t == null)
				{
					t = AutoKeyBoardTab.GetVisualChild<T>(visual);
				}
				if (t != null)
				{
					break;
				}
			}
			return t;
		}

		private void btnDelete_Click(object sender, RoutedEventArgs e)
		{
			KeyBoardItem keyBoardItem = this.dataGrid.SelectedItem as KeyBoardItem;
			if (keyBoardItem.CmdName != "")
			{
				KeyBoardItem keyBoardItem2 = this.dataGrid.Items[this.dataGrid.SelectedIndex + 1] as KeyBoardItem;
				if (keyBoardItem2.CmdName == string.Empty)
				{
					keyBoardItem2.CmdName = keyBoardItem.CmdName;
					keyBoardItem.CommandInfos.KeyBoardName = keyBoardItem.CommandInfos.KeyBoardName.Replace(keyBoardItem.KeyBoard + "#", "");
					this.dataGrid.Items.Remove(this.dataGrid.SelectedItem);
					this.m_DicKeyBoard.Remove(keyBoardItem.CmdName);
					return;
				}
				this.SetCellValue("");
				if (keyBoardItem.CommandInfos.KeyBoardName != string.Empty)
				{
					keyBoardItem.CommandInfos.KeyBoardName = keyBoardItem.CommandInfos.KeyBoardName.Replace(keyBoardItem.KeyBoard, "");
					this.m_DicKeyBoard.Remove(keyBoardItem.CmdName);
					return;
				}
			}
			else
			{
				keyBoardItem.CommandInfos.KeyBoardName = keyBoardItem.CommandInfos.KeyBoardName.Replace("#" + keyBoardItem.KeyBoard, "");
				this.dataGrid.Items.Remove(this.dataGrid.SelectedItem);
				this.m_DicKeyBoard.Remove(keyBoardItem.CmdName);
			}
		}

		private void txtKey_PreviewTextInput(object sender, TextCompositionEventArgs e)
		{
			Regex regex = new Regex("[^A-Za-z0-9]");
			e.Handled = regex.IsMatch(e.Text);
		}

		private void txtKey_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
		{
			if (e.Key == Key.Space)
			{
				e.Handled = true;
			}
		}

        //[DebuggerNonUserCode]
        //[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
        //public void InitializeComponent()
        //{
        //    if (this._contentLoaded)
        //    {
        //        return;
        //    }
        //    this._contentLoaded = true;
        //    Uri resourceLocator = new Uri("/YJKMenuAssist;component/menumanagecontrols/autokeyboardtab.xaml", UriKind.Relative);
        //    System.Windows.Application.LoadComponent(this, resourceLocator);
        //}

        //[DebuggerNonUserCode]
        //[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
        //internal Delegate _CreateDelegate(Type delegateType, string handler)
        //{
        //    return Delegate.CreateDelegate(delegateType, this, handler);
        //}

        //[DebuggerNonUserCode]
        //[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
        //[EditorBrowsable(EditorBrowsableState.Never)]
        //void IComponentConnector.Connect(int connectionId, object target)
        //{
        //    switch (connectionId)
        //    {
        //    case 1:
        //        this.autoKeyBoardTabGrid = (AutoKeyBoardTab)target;
        //        return;
        //    case 2:
        //        this.label = (System.Windows.Controls.Label)target;
        //        return;
        //    case 3:
        //        this.leftList = (LeftList)target;
        //        return;
        //    case 4:
        //        this.dataGrid = (System.Windows.Controls.DataGrid)target;
        //        this.dataGrid.SelectionChanged += this.dataGrid_SelectionChanged;
        //        return;
        //    case 5:
        //        this.textBox = (System.Windows.Controls.TextBox)target;
        //        this.textBox.GotFocus += this.textBox_GotFocus;
        //        this.textBox.LostFocus += this.textBox_LostFocus;
        //        this.textBox.TextChanged += this.textBox_TextChanged;
        //        return;
        //    case 6:
        //        this.tbKey = (TextBlock)target;
        //        return;
        //    case 7:
        //        this.txtKey = (System.Windows.Controls.TextBox)target;
        //        this.txtKey.PreviewKeyDown += this.txtKey_PreviewKeyDown;
        //        this.txtKey.PreviewTextInput += this.txtKey_PreviewTextInput;
        //        this.txtKey.TextChanged += this.txtKey_TextChanged;
        //        return;
        //    case 8:
        //        this.btnAdd = (System.Windows.Controls.Button)target;
        //        this.btnAdd.Click += this.btnAdd_Click;
        //        return;
        //    case 9:
        //        this.btnDelete = (System.Windows.Controls.Button)target;
        //        this.btnDelete.Click += this.btnDelete_Click;
        //        return;
        //    default:
        //        this._contentLoaded = true;
        //        return;
        //    }
        //}

		private CommandTableInfos m_CommandTableInfos;

		private ExternalCommandData m_CommandData;

		private List<string> m_LstKeyBoard = new List<string>();

		private Dictionary<string, CommandInfos> m_DicKeyBoard = new Dictionary<string, CommandInfos>();

        //internal AutoKeyBoardTab autoKeyBoardTabGrid;

        //internal System.Windows.Controls.Label label;

		internal LeftList leftList;

        //internal System.Windows.Controls.DataGrid dataGrid;

        //internal System.Windows.Controls.TextBox textBox;

        //internal TextBlock tbKey;

        //internal System.Windows.Controls.TextBox txtKey;

        //internal System.Windows.Controls.Button btnAdd;

        //internal System.Windows.Controls.Button btnDelete;

        //private bool _contentLoaded;
	}
}
